from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.views import APIView

from oauth.exceptions import QQAPIError
from oauth.models import oAuthQQuser
from oauth.utils import OAuthQQ


class QQAuthURLView(APIView):
    def get(self, request):
        next = request.query_params.get('next')
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_qq_login_url()
        return Response({'login_url': login_url})

# /qq/user/?code=xxx
class QQAuthUserView(APIView):
    def get(self, request):
        code = request.query_params.get('code')
        if not code:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        oauth = OAuthQQ()
        try:
            access_token=oauth.get_access_token(code)
            openid=oauth.get_openid(access_token)
        except QQAPIError:
            return Response({'message':'QQ服务器'},status=status.HTTP_503_SERVICE_UNAVAILABLE)
        try:
            qq_user=oAuthQQuser.objects.get(openid=openid)
        except oAuthQQuser.DoesNotExist:
            token=oauth.generate_save_user_token(openid)
            return Response({'access_token':token})
        else:
            # 找到用户, 生成token
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            return response